package com.yuwenchao.superafflatus.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.yuwenchao.superafflatus.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Api(tags = "阿里云对象存储")
@RestController
@RequestMapping("/al")
public class AlOssUpdateController {
/*
    @Autowired
    OSS ossClient;*/

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretKey;


    /**
     * 文件上传
     * 该方法正常使用,但是ossClient 方法过时
     * @param avatar
     */
    @ApiOperation(value = "阿里云图片上传")
    @PostMapping("avatar/upload")
    public R upload(
            @ApiParam(name = "avatar", value = "文件", required = false)
            @RequestParam("avatar") MultipartFile avatar) {

        String uploadUrl = null;

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
           // OSSClient ossClient = new OSSClient(endpoint, accessId, secretKey);  该方法过时
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, secretKey);
            if (!ossClient.doesBucketExist(bucket)) {
                //创建bucket
                ossClient.createBucket(bucket);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucket, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = avatar.getInputStream();

            //构建日期路径：avatar/2019/02/26/文件名
            //String filePath = new DateTime().toString("yyyy/MM/dd");

            //文件名：uuid.扩展名
            String original = avatar.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = "avatar" +  "/" + newName;

            //文件上传至阿里云
            ossClient.putObject(bucket, fileUrl, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            //https://chao-mall.oss-cn-beijing.aliyuncs.com/avatar/2022/01/14/ce650e14-255a-48a1-a0ed-d8cff764dd33.jpg
           // avatar/2022/01/14/ce650e14-255a-48a1-a0ed-d8cff764dd33.jpg
            //获取url地址
            uploadUrl = "http://" + bucket + "." + endpoint + "/" + fileUrl;
            //https://chao-mall.oss-cn-beijing.aliyuncs.com/avatar/9e176a55-6bc2-4b43-821c-ca5a94fe4b84.jpg

        } catch (IOException e) {

        }
       // System.out.println("返回值:"+uploadUrl);
        //返回r对象
        return R.ok().message("文件上传成功").data("url", uploadUrl);

    }


    //kenan.jpg
    @ApiOperation(value = "阿里云图片下载")
    @PostMapping("avatar/download")
    public R aldownload(String objectName){


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, secretKey);

        String key = "D:\\"+objectName;
// 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
// 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        ossClient.getObject(new GetObjectRequest(bucket, objectName), new File(key));

// 关闭OSSClient。
        ossClient.shutdown();

        return  R.ok().data("url",key);
    }
}
